package com.shiroexploit.task;

import com.shiroexploit.util.Config;
import javafx.concurrent.Task;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetDNSLogRecordTask extends Task<Integer> {

    private int status = 0;
    private Config config;

    public int getStatus(){
        return status;
    }

    public GetDNSLogRecordTask(Config config){
        this.config = config;
    }

    @Override
    protected Integer call(){
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();

        try
        {
            connection = (HttpURLConnection)new URL("http://www.dnslog.cn/getdomain.php").openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                String sessinoId = connection.getHeaderField("Set-Cookie");
                sessinoId = sessinoId.split(";")[0];

                inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }

                Config.getInstance().setSessionId(sessinoId);
                Config.getInstance().setDnsLogRecord(sb.toString());
                status = 1;
                return 1;
            }
        }
        catch (IOException e) {
            status = -1;
            return 1;
        } finally {
            try {
                if (connection != null) connection.disconnect();
                if (inputStream != null) inputStream.close();
                if (reader != null) reader.close();
            } catch (IOException e) {
                status = -1;
                return 1;
            }
        }

        status = -1;
        return 1;
    }
}
